/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.crystalrange.documents.web;

import org.crystalrange.BaseController;
import org.crystalrange.Message;
import org.crystalrange.documents.model.DocumentTag;
import org.crystalrange.documents.service.DocumentTagService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.Clients;

/**
 *
 * @author Krzysiek
 */
public class DocumentTagController extends BaseController {
    
    private DocumentTag documentTag;
    private DocumentTagService documentTagService;

    public DocumentTag getDocumentTag() {
        return documentTag;
    }

    public void setDocumentTag(DocumentTag documentTag) {
        this.documentTag = documentTag;
    }

    public DocumentTagService getDocumentTagService() {
        return documentTagService;
    }

    public void setDocumentTagService(DocumentTagService documentTagService) {
        this.documentTagService = documentTagService;
    }
    
    public void onClick$toolbarbuttonDocumentTagSave(Event event) throws Exception {
        this.documentTagSave();
    }
    
    public void onClick$menuitemDocumentTagSave(Event event) throws Exception {
        this.documentTagSave();        
    } 
    
    private void documentTagSave() throws Exception {
    	if (this.documentTag.getName() != null) {
    		this.documentTagService.save(this.documentTag);
    		this.sessionScope.put("CRYSTALRANGE_MESSAGE", new Message("Saved successfully!"));
    		Clients.evalJavaScript("window.history.back();");
		} else {
			this.message.setText("You must enter 'Tag Name'.");
            this.message.setIcon("/img/exclamation.png");
            this.binder.loadAll();
		}
    }
    
    @Override
    public void doAfterCompose(Component component) throws Exception {
        super.doAfterCompose(component);
        
        if (this.execution.getParameter("Id") != null) {
            this.documentTag = this.documentTagService.find(
                    Long.parseLong(this.execution.getParameter("Id")));
            this.labelTitle.setValue("Edit Document Tag");
        } else {
            this.documentTag = this.documentTagService.create(
                    SecurityContextHolder.getContext().getAuthentication().getName());
            this.labelTitle.setValue("Create Document Tag");
        }
        
        component.setAttribute("controller", this);
    }
}
